package com.tencent.libpag.sample.libpag_sample.codec;

import android.annotation.TargetApi;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.os.Build;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class Mp3Deal {



	private static final int SAMPLE_SIZE = 1024 * 200;




	/**
	 *
	 * @param inputPath 被截取音频路径
	 * @param outputPath 输出音频路径
	 * @param start 截取开始时间  单位:秒
	 * @param end   截取结束时间  单位:秒
	 * @return
	 * @throws IOException
	 */
	public static boolean clip(String inputPath, String outputPath, int start, int end) throws IOException {
		MediaExtractor extractor ;
		BufferedOutputStream outputStream;
		File file = new File(outputPath);
		if (file.exists()) {
			file.delete();
		}
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		extractor = new MediaExtractor();
		extractor.setDataSource(inputPath);
		int track = getAudioTrack(extractor);
		if (track < 0) {
			return false;
		}
		//选择音频轨道
		extractor.selectTrack(track);
		outputStream = new BufferedOutputStream(
				new FileOutputStream(outputPath), SAMPLE_SIZE);
		start = start * 1000;
		end = end * 1000;
		//跳至开始裁剪位置
		extractor.seekTo(start, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
		while (true) {
			ByteBuffer buffer = ByteBuffer.allocate(SAMPLE_SIZE);
			int sampleSize = extractor.readSampleData(buffer, 0);

			long timeStamp = extractor.getSampleTime();
			if (timeStamp > end ) {
				break;
			}
			if (sampleSize <= 0) {
				break;
			}
			byte[] buf = new byte[sampleSize];
			buffer.get(buf, 0, sampleSize);
			//写入文件
			outputStream.write(buf);
			//音轨数据往前读
			extractor.advance();
		}
		if (extractor != null) {
			extractor.release();
		}
		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
	/**
	 * 获取音频数据轨道
	 *
	 * @param extractor
	 * @return
	 */
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private static int getAudioTrack(MediaExtractor extractor) {
		for (int i = 0; i < extractor.getTrackCount(); i++) {
			MediaFormat format = extractor.getTrackFormat(i);
			String mime = format.getString(MediaFormat.KEY_MIME);
			if (mime.startsWith("audio")) {
				return i;
			}
		}
		return -1;
	}

}
